Python PathLib .iterdir() Explanation (PC Draft) Page-02

1. Tutorial: .iterdir()

If you only need to list the contents of a given directory,
and you don't need to get the contents of each subdirectory too,
then you can use the Path object's .iterdir() method.
If your aim is to move through directories and subdirectories recursively,
then you can jump ahead to the section on recursive listing.

The .iterdir() method, when called on a Path object,
returns a generator that yields Path objects representing child items.
If you wrap the generator in a list() constructor,
then you can see your list of files and folders:

            
                import pathlib
                desktop = pathlib.Path("Desktop")

                # .iterdir() produces a generator
                desktop.iterdir()
                
                # print(desktop.iterdir()) generator
                generator object Path.iterdir at 0x000001A8A5110740>
                
                # Wrap the Generator in a list() constructor,  
                # Then you can see your list of files and folders
                list(desktop.iterdir())
                
                # Output
                [WindowsPath('Desktop/Notes'),
                WindowsPath('Desktop/realpython'),
                WindowsPath('Desktop/scripts'),
                WindowsPath('Desktop/todo.txt')]
                
                # Now you can save the iterdir-list into a variable 
                Dirs_list = list(desktop.iterdir())
            
        

Passing the generator produced by .iterdir() to the list() constructor
provides you with a list of Path objects representing all the items in the Desktop directory.

As with all generators, you can also use a For-Loop to iterate over each item that the generator yields.
This gives you the chance to explore some of the properties of each object:

            
                # desktop: The list of Path objects representing all the items in the Desktop directory
                desktop = pathlib.Path("Desktop")
                
                # As with all generators, you can also use a For-Loop to iterate over each item 
                # that the generator yields
                for item in desktop.iterdir():
                    print(f"{item} - {"dir" if item.is_dir() else "file"}")
                
                # Output
                Desktop\Notes - dir
                Desktop\realpython - dir
                Desktop\scripts - dir
                Desktop\todo.txt - file

                # Other Output Examples
                # Of what you can do with the Files or Folders found in the Directory
                p = Path("/home/max/docs/report.pdf")
                p.name       # "report.pdf"
                p.stem       # "report"
                p.suffix     # ".pdf"
                p.suffixes   # [".tar", ".gz"]
                p.parent     # "/home/max/docs"
                p.parents[0] # "/home/max/docs"
                p.parents[1] # "/home/max"

                
            
        
2. Creating Paths
            
                # Current working directory
                p = Path.cwd()
    
                # Home directory
                home = Path.home()
    
                # Relative path
                p = Path("folder/subfolder/file.txt")
    
                # Absolute path
                p = Path("/usr/local/bin")
    
                # Convert to string
                str_path = str(p)
            
        
# This tag will be opened by default.